package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.convertor.EmployeeConvertor;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Validated
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    EmployeeService employeeService;

    //构建DTO转实体类，实体类转dto
    private final EmployeeConvertor employeeConvertor = EmployeeConvertor.INSTANCE;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //MD5加密
        String s = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        if (!s.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param req 新增员工数据
     * @return 是否插入成功
     */
    @Override
    public Boolean employee(EmployeeDTO req){
        //dto转换实体类
        Employee employee = employeeConvertor.convertorToException(req);
        //状态赋值
        employee.setStatus(StatusConstant.ENABLE);
        //将密码进行赋值
        employee.setPassword(PasswordConstant.DEFAULT_PASSWORD);

        //增加创建人和修改人
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        //增加创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //查看账号是否存在
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        List<Employee> list = employeeService.list(qw);
        if (!CollectionUtils.isEmpty(list)) {
            throw new PasswordErrorException(MessageConstant.ACCOUNT_PRE_FOUND);
        }
        //存库操作并返回
        return employeeService.save(employee);
    }

    /**
     * 查询员工信息
     * @param employeePageQueryDTO 查询员工信息入参
     * @return 员工信息
     */
    public PageResult getEmployeeList(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> employeeList = employeeMapper.getEmployeeList(employeePageQueryDTO);
        return new PageResult(employeeList.getTotal(), employeeList.getResult());
    }

    /**
     * 查询员工信息
     * @param employeePageQueryDTO 查询员工信息入参
     * @return 员工信息
     */
    public PageResult getEmployeePage(EmployeePageQueryDTO employeePageQueryDTO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Employee> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Employee> page1 = employeeMapper.selectPage(page, new LambdaQueryWrapper<>());
        return new PageResult(page1.getTotal(), page1.getRecords());
    }

    /**
     * 禁用员工
     * @param id 禁用员工id
     * @return 是否成功
     */
    public Boolean disable(Long id, Integer status) {
        log.info("变更的id:{}",id);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getId,id);
        Employee employee = new Employee();
        employee.setStatus(status);
        employeeMapper.update(employee,qw);
    return true;
    }

    //查询账号详情
    public Employee getEmployeeDetails(Long id) {
        return employeeMapper.selectById(id);
    }

    public Boolean updateEmployeeInfo(EmployeeDTO req) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(req,employee);
        //校验
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee employeeOne = employeeMapper.selectOne(qw);
        if (ObjectUtil.isNotEmpty(employeeOne)) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_PRE_FOUND);
        }
        //修改操作
        int updateById = employeeMapper.updateById(employee);
        //判断
        if (updateById != 1) {
            throw new AccountLockedException(MessageConstant.UPDATE_DATE_NO);
        }
        return true;
    }
}
